cc.Class({
    extends: cc.Component,

    properties: {
        partSale: require('ShopPartSale'),
        partBags: require('ShopPartBags'),
        partLeaf: require('ShopPartLeaf'),
        txtSale: cc.Label,
        txtBags: cc.Label,
        txtLeaf: cc.Label
    },

    onLoad () {
        this.txtSale.string = LangPublic.W101;
        this.txtBags.string = LangPublic.W102;
        this.txtLeaf.string = LangPublic.W103;
        this.partSale.node.parent = null;
        this.partBags.node.parent = null;
        this.partLeaf.node.setLocalZOrder(1000);
        cc.Emitter.on(EVENTS.GAME_RECHARGE, this.onRecharge, this);
    },

    start() {
        this.container = this.node.find('layout');
        if(cc.GameProxy) {
            cc.Linker(URL.ShopList).request(data => this.renderLeafList(data));
            cc.Linker(URL.SaleList).request(data => this.renderSaleLists(data));
        } else {
            cc.Linker(URL.ShopList).request(this.renderLeafList, this);
            cc.Linker(URL.SaleList).request(this.renderSaleLists, this);
        }
    },

    onDestroy() {
        cc.Emitter.off(EVENTS.GAME_RECHARGE, this.onRecharge, this);
    },
    
    onRecharge(orderId) {
        cc.Linker(URL.ShopBought, {
            convertId: orderId
        }).showMessage(false).request(data => cc.Popup.show('public/ShopGotPop', pop => pop.init(data)));
    },
    
    initLists() {
        if(!this.leafData || !this.saleData) return;
        var data = this.saleData; 
        for(var i in data) {
            var d = data[i];
            if(d.position == 0) {
                this.addSaleItem(d);
                this.addBagsItem(d);
            } else if (d.position == 1) {
                this.addSaleItem(d);
            } else {
                this.addBagsItem(d);
            }
        }
        if(this.partSale.node.parent == null) this.partLeaf.node.height += 344;
        if(this.partBags.node.parent == null) this.partLeaf.node.height += 254;
    },

    renderLeafList(data) {
        if(this.leafData && this.saleData) return;
        this.partLeaf.init(data);
        this.leafData = data;
        this.initLists();
    },

    renderSaleLists(data) {
        if(this.leafData && this.saleData) return;
        this.saleData = data;
        this.initLists();
    },

    addSaleItem(data) {
        if(this.partSale.node.parent == null) {
            this.partLeaf.node.setLocalZOrder(10);
            this.partSale.node.parent = this.container;
        }
        this.partSale.addItem(data);
    },

    addBagsItem(data) {
        if(this.partBags.node.parent == null) {
            this.partLeaf.node.setLocalZOrder(100);
            this.partBags.node.parent = this.container;
        }
        this.partBags.addItem(data);
    }

});
